package cn.framelife.rainbow.db;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import cn.framelife.rainbow.db.entity.ForeignKey;
import cn.framelife.rainbow.util.StringUtil;

/**
 * 数据表相关
 *
 * @author 潘广伟  p_3er@qq.com 
 * @date 2013年11月23日 下午4:28:50 
 *
 */
public abstract class BaseTable {
	private String tableName; 
	private DatabaseMetaData metaData;

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public DatabaseMetaData getMetaData() {
		return metaData;
	}

	public void setMetaData(DatabaseMetaData metaData) {
		this.metaData = metaData;
	}

	public BaseTable(String tableName,DatabaseMetaData metaData){
		this.tableName = tableName;
		this.metaData = metaData;
	}

	/**
	 * 获取数据表的备注
	 *
	 * @param tableName
	 * @return
	 * @throws Exception
	 */
	public String getTableComment(String tableName) throws Exception{
		String tableComment = this.getTableComment(tableName, metaData.getConnection());
		if(!StringUtil.isNotEmpty(tableComment)){
			tableComment = tableName;
		}  
		
		return tableComment;
	}
	
	public abstract String getTableComment(String tableName, Connection conn) throws Exception;
	
	/**
	 * 获取主键的名称（单个主键）
	 *
	 * @Title: getPKColumnName 
	 * @param @param metaData
	 * @param @param tableName
	 * @param @return
	 * @param @throws SQLException  
	 * @return String  
	 * @throws
	 */
	public String getPKColumnName()
			throws SQLException {
		ResultSet pkSet = metaData.getPrimaryKeys(null, null, tableName); 
		String pkName = "id";
		while( pkSet.next() ) { 
			pkName = pkSet.getString("COLUMN_NAME");
		}
		return pkName;
	}
	
	/**
	 * 获取外键信息
	 *
	 * @Title: getFKColumn 
	 * @param @return
	 * @param @throws Exception  
	 * @return List<ForeignKey>  
	 * @throws
	 */
	public Map<String,ForeignKey> getFKColumn() throws Exception{
		ResultSet fkSet = metaData.getImportedKeys(null, null, tableName);
		Map<String,ForeignKey> fks = new HashMap<String, ForeignKey>();
		while(fkSet.next()) { 
			ForeignKey fk = new ForeignKey();
			fk.setOriginName(fkSet.getString("PKCOLUMN_NAME"));
			fk.setFkName(fkSet.getString("FKCOLUMN_NAME"));
			fk.setFkTableName(fkSet.getString("PKTABLE_NAME"));
			fks.put(fk.getFkName(), fk);
		}
		return fks;
	}
}
